package com.ljd.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ljd.gulimall.product.entity.CategoryBrandRelationEntity;
import com.ljd.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljd.common.utils.PageUtils;
import com.ljd.common.utils.Query;

import com.ljd.gulimall.product.dao.BrandDao;
import com.ljd.gulimall.product.entity.BrandEntity;
import com.ljd.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(key)) {
            wrapper.and(ew -> ew.eq("brand_id", key).or().like("name", key));
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void updateCascode(BrandEntity brand) {
        this.updateById(brand);

        Long brandId = brand.getBrandId();
        String name = brand.getName();

        if(StringUtils.isNotBlank(name)) {
            CategoryBrandRelationEntity relation = new CategoryBrandRelationEntity();
//            relation.setBrandId(brandId);
            relation.setBrandName(name);
            categoryBrandRelationService.update(relation, new UpdateWrapper<CategoryBrandRelationEntity>()
                    .eq("brand_id", brandId));
        }
    }

}